package com.mbc.web.common.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.mbc.web.common.shared.HttpStatus;
import com.mbc.common.entities.Currency;
import com.mbc.web.common.client.ButtonActionType;
import com.mbc.web.common.client.ClientSingleton;
import com.mbc.web.common.client.CommonControllerMgr;
import com.mbc.web.common.client.CommonMessage;
import com.mbc.web.common.client.ViewUtils;
import com.mbc.web.common.client.ui.control.MButton;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.mbc.web.common.client.ui.control.MTextBox;

public class FrmCurrency extends Composite {

	@UiField MButton btnSave;
	@UiField MButton btnEdit;
	@UiField MButton btnDelete;
	@UiField MButton btnReset;
	@UiField MButton btnNew;
	@UiField MButton btnBack;
	@UiField MButton btnList;
	@UiField MTextBox txtCurrencyCode;
	@UiField MTextBox txtDescription;
	@UiField MTextBox txtSymbol;
	@UiField MTextBox txtDecimal;
	@UiField MTextBox txtMMDescription;
	
	private long currencyId;
	private Currency currency;
	private byte action_type;
	
	private static FrmCurrencyUiBinder uiBinder = GWT
			.create(FrmCurrencyUiBinder.class);

	interface FrmCurrencyUiBinder extends UiBinder<Widget, FrmCurrency> {
	}

	public FrmCurrency() {
		initWidget(uiBinder.createAndBindUi(this));
		initialize();
		onBtnNewClick(null);
	}
	
	public FrmCurrency(Currency currency){
		initWidget(uiBinder.createAndBindUi(this));
		initialize();
		this.currency = currency;
		bindControls(currency);
		enableControls(false);
		btnSave.setEnabled(false);
		btnEdit.setEnabled(true);
		btnDelete.setEnabled(true);
		btnReset.setEnabled(false);
	}
	
	private void initialize(){
		
		txtCurrencyCode.getElement().setAttribute("style", "text-transform: uppercase;");
		
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			
			@Override
			public void execute() {
				txtCurrencyCode.setFocus(true);
			}
		});
		txtDecimal.addKeyDownHandler(new KeyDownHandler() {
			
			@Override
			public void onKeyDown(KeyDownEvent event) {
				if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
					event.preventDefault();
					TextBox l_txt = (TextBox) event.getSource();
					if(l_txt == txtDecimal)
						btnSave.setFocus(true);
				}
			}
		});
	}
	
	private void enableControls(boolean enabled){
		txtCurrencyCode.setEnabled(enabled);
		txtDecimal.setEnabled(enabled);
		txtDescription.setEnabled(enabled);
		txtSymbol.setEnabled(enabled);
		txtMMDescription.setEnabled(enabled);
	}
	
	private native void jsClear()/*-{
		$wnd.$("input").val("");
	}-*/;
	
	private void clear(){
		jsClear();
		ViewUtils.clearRequiredNotifications();
		currencyId = 0;
		currency = null;
	}

	private void bindControls(Currency currency){
		txtCurrencyCode.setText(currency.getCurrencyCode());
		txtDecimal.setText(String.valueOf(currency.getDecimalPlace()));
		txtSymbol.setText(currency.getSymbol());;
		txtDescription.setText(currency.getDescription());
		txtMMDescription.setText(currency.getMyanmarDescription());
		
		currencyId = currency.getCurrencyId();
	}
	
	private Currency bindCurrency(){
		Currency l_currency = new Currency();
		l_currency.setCurrencyId(currencyId);
		l_currency.setCurrencyCode(txtCurrencyCode.getText().toUpperCase());
		l_currency.setDescription(txtDescription.getText());
		l_currency.setSymbol(txtSymbol.getText());
		l_currency.setMyanmarDescription(txtMMDescription.getText());
		l_currency.setDecimalPlace(Byte.parseByte(txtDecimal.getText()));
		return l_currency;
	}
	
	private AsyncCallback<Integer> actionCallback()
	{
		return new AsyncCallback<Integer>() {
			
			@Override
			public void onSuccess(Integer result) {
				ViewUtils.stopAjaxLoader();
				if(result == HttpStatus.OK){
					switch (action_type) {
					case ButtonActionType.action_save:
						ViewUtils.showSuccessMessage(CommonMessage.saved_message);
						ClientSingleton.changeView(new SearchCurrency(txtCurrencyCode.getText(), SearchCurrency.SAVE));
						break;
					case ButtonActionType.action_delete:
						ViewUtils.showSuccessMessage(CommonMessage.deleted_message);
						ClientSingleton.changeView(new SearchCurrency(txtCurrencyCode.getText(), SearchCurrency.DELETE));
						break;
					}
				}
				else{
					switch (result) {
					case HttpStatus.INTERNAL_SERVER_ERROR:
						ViewUtils.showErrorMessage(CommonMessage.internal_server_error_message);
						break;
					case HttpStatus.BAD_REQUEST:
						ViewUtils.showErrorMessage(CommonMessage.getAlreadyExistedMessage("Currency Code(" + txtCurrencyCode.getText() + ")"));
						break;
					case HttpStatus.FORBIDDEN:
						ViewUtils.showErrorMessage(CommonMessage.getDataCannotDeleteMessage("Currency Code(" + txtCurrencyCode.getText() + ")"));
						break;
					}
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	@UiHandler("btnNew")
	void onBtnNewClick(ClickEvent event) {
		clear();
		enableControls(true);
		txtCurrencyCode.setFocus(true);
		btnSave.setEnabled(true);
		btnEdit.setEnabled(false);
		btnDelete.setEnabled(false);
		btnReset.setEnabled(false);
	}
	
	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent event) {
		if(ViewUtils.isValidate()){
			action_type = ButtonActionType.action_save;
			ViewUtils.startAjaxLoader(CommonMessage.saving_message);
			if(currencyId == 0)
				CommonControllerMgr.createCurrency(bindCurrency(), actionCallback());
			else
				CommonControllerMgr.updateCurrency(bindCurrency(), actionCallback());
		}
	}
	
	@UiHandler("btnEdit")
	void onBtnEditClick(ClickEvent event) {
		if(currencyId != 0)
		{
			btnReset.setEnabled(true);
			btnSave.setEnabled(true);
			btnEdit.setEnabled(false);
			btnNew.setEnabled(false);
			enableControls(true);
			txtDescription.setFocus(true);
			txtCurrencyCode.setEnabled(false);
		}
	}
	
	@UiHandler("btnDelete")
	void onBtnDeleteClick(ClickEvent event) {
		if(currencyId != 0)
		{
			ViewUtils.showConfirm(CommonMessage.delete_confirm_message, new CloseHandler<PopupPanel>() {
				
				@Override
				public void onClose(CloseEvent<PopupPanel> event) {
					if(ViewUtils.isAlertYes()){
						action_type = ButtonActionType.action_delete;
						ViewUtils.startAjaxLoader(CommonMessage.deleting_message);
						CommonControllerMgr.deleteCurrency(currencyId, actionCallback());
					}
				}
			});
		}
	}
	
	@UiHandler("btnReset")
	void onBtnResetClick(ClickEvent event) {
		bindControls(currency);
		enableControls(false);
		btnReset.setEnabled(false);
		btnSave.setEnabled(false);
		btnEdit.setEnabled(true);
		btnNew.setEnabled(true);
	}
	
	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		ClientSingleton.changeView(new SearchCurrency());
	}
	
	@UiHandler("btnList")
	void onBtnListClick(ClickEvent event) {
		ClientSingleton.changeView(new FrmCurrencyRpt());
	}
}
